import Url from 'url';
import Config from './config';
import Proxy from './proxy';
import Utils from './modules/utils';
import cdnApp from './cdnApp';
import ProxyRulesParser from './modules/proxyRulesParser';

export default App;

function App(req, res){

    /*
    * if Config.filterRequest,there might res.end executed
    * rewrite res.end to prevent "Error: Can't set headers after they are sent."
    */
    let _resEnd=res.end.bind(res);
    res.end=function(){
      _resEnd.apply(null,arguments);
      this.__ended=1;
    }
    if(Config.filterRequest&&Utils.getArgtype(Config.filterRequest)=='function'){
      Config.filterRequest(req,res);
      if(res.__ended) {
        res.__ended=null;
        return false;
      }
    }
    
    ProxyRulesParser(req,res,proxyRule=>{
      console.log(proxyRule)
      if (!proxyRule) {
        console.log('redirect to static')
        res.end('redirect to static');
        // redirect to static
      }else{
        if (proxyRule.proxyType==1) {
          Proxy.web(req, res, { target:proxyRule.proxyTarget });
        }else{
          cdnApp(req,res)(proxyRule.proxyTarget);
        };
      };
    });  
    
   //  if(req.headers['user-agent']&&
   //    req.headers['user-agent'].toLowerCase().indexOf('mobile')!=-1&&
   //    host!='images.famanoder.com'&&
   //    host!='cdn.famanoder.com'&&
   //    req.url.indexOf('ajaxPage')==-1){
   //      host='m.famanoder.com';
   //  };
   //  switch (host){
   //    case 'images.famanoder.com':
   //      Proxy.web(req, res, { target: 'https://localhost:6000' });
   //    break;
   //    case 'm.famanoder.com':
   //      Proxy.web(req, res, { target: 'https://localhost:5000' });
   //    break;
   //    case 'cdn.famanoder.com': 
   //        console.log(req.connection.remoteAddress);
   //      Proxy.web(req, res, { target: 'https://localhost:4000' });
   //    break;
   //    default:  
   //      Proxy.web(req, res, { target: 'http://localhost:9000' });
   // }
}



